package cn.tedu.demo.service.impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.tedu.demo.service.FileService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;

@Service
public class FileServiceImpl implements FileService {
    @Value("${server.port}")
    private String port;

    private static final String ip="http://localhost:";

    @Override
    @Transactional
    public String upload(MultipartFile file) throws IOException {
        String filename = file.getOriginalFilename();
        String flag = IdUtil.fastSimpleUUID();
        String footFilePath=System.getProperty("user.dir")+"/springboot/src/main/resources/files/"+flag+"_"+filename;
        FileUtil.writeBytes(file.getBytes(),footFilePath);
        String path=ip+port+"/files/"+flag;
        return path;
    }

    @Override
    public void getFiles(String flag, HttpServletResponse response) {
        OutputStream os;  // 新建一个输出流对象
        String basePath = System.getProperty("user.dir") + "/springboot/src/main/resources/files/";
        List<String> fileNames = FileUtil.listFileNames(basePath);  // 获取所有的文件名称
        String fileName = fileNames.stream().filter(name -> name.contains(flag)).findAny().orElse("");  // 找到跟参数一致的文件
        try {
            if (StrUtil.isNotEmpty(fileName)) {
                response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
                response.setContentType("application/octet-stream");
                byte[] bytes = FileUtil.readBytes(basePath + fileName);  // 通过文件的路径读取文件字节流
                os = response.getOutputStream();   // 通过输出流返回文件
                os.write(bytes);
                os.flush();
                os.close();
            }
        } catch (Exception e) {
            System.out.println("文件下载失败");
        }
    }

    @Override
    public JSON editorUpload(MultipartFile file) throws IOException {
        String filename = file.getOriginalFilename();
        String flag = IdUtil.fastSimpleUUID();
        String footFilePath=System.getProperty("user.dir")+"/springboot/src/main/resources/files/"+flag+"_"+filename;
        FileUtil.writeBytes(file.getBytes(),footFilePath);
        String url=ip+port+"/files/"+flag;
        JSONObject json = new JSONObject();
        json.set("errno",0);
        JSONArray arr = new JSONArray();
        JSONObject data = new JSONObject();
        arr.add(data);
        data.set("url",url);
        json.set("data",arr);
        return json;
    }
}
